//---------------------------------------------------------------------
// Authors: jachymko
//
// Description: Class for passing segments of byte arrays.
//
// Creation Date: Dec 24, 2006
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Pscx {
    public struct BufferSegment : IEnumerable<byte> {

        byte[] buffer;
        uint offset;
        uint count;

        public BufferSegment(byte[] buffer)
            : this(buffer, 0, (uint)(buffer.Length)) {
        }

        public BufferSegment(byte[] buffer, uint offset)
            : this(buffer, offset, (uint)(buffer.Length - offset)) {
        }

        public BufferSegment(byte[] buffer, uint offset, uint count) {
            Throw.IfIsNullOrEmpty(buffer);
            Throw.ArgumentOutOfRangeExceptionIf(count == 0);
            Throw.ArgumentOutOfRangeExceptionIf(count > buffer.Length - offset);

            this.buffer = buffer;
            this.offset = offset;
            this.count = count;
        }

        public byte this[uint index] {
            get { return buffer[offset + index]; }
        }

        public byte[] Buffer {
            get { return buffer; }
            set { buffer = value; }
        }

        public uint Offset {
            get { return offset; }
            set { offset = value; }
        }

        public uint Count {
            get { return count; }
            set { count = value; }
        }

        public IEnumerator<byte> GetEnumerator() {
            for (uint i = offset; i < offset + count; i++) {
                yield return buffer[i];
            }
        }

        public MemoryStream OpenStream() {
            return OpenStream(false);
        }
        public MemoryStream OpenStream(bool writable) {
            return OpenStream(writable, false);
        }
        public MemoryStream OpenStream(bool writable, bool publiclyVisible) {
            return new MemoryStream(buffer, (int)offset, (int)count, writable, publiclyVisible);
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
            return this.GetEnumerator();
        }
   }
}
